package nacos

import (
	viperc "flare-admin/config/viper"
	"os"
	"strings"

	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

// Internal
var (
	clientConfig = constant.ClientConfig{
		NamespaceId: "public",
	}
	serverConfig = []constant.ServerConfig{
		//{
		//	IpAddr: "10.176.40.186",
		//	Port:   8848,
		//	Scheme: "http",
		//},
	}
)

var (
	// NacosClient 单例Nacos客户端
	NacosClient config_client.IConfigClient
)

func init() {
	c, err := NewNacosClient()
	if err != nil {
		panic(err)
	}
	NacosClient = c

	nacosLoad()
}

func NewNacosClient() (config_client.IConfigClient, error) {
	// 获取application.yaml中的配置
	clientConfig.NamespaceId = viperc.BootCfg.Nacos.Client.NamespaceId
	for _, each := range viperc.BootCfg.Nacos.Server {
		serverConfig = append(serverConfig, constant.ServerConfig{
			IpAddr: each.Addr,
			Port:   each.Port,
			Scheme: each.Scheme,
		})
	}

	// 创建Nacos客户端
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfig,
		},
	)

	if err != nil {
		return nil, err
	}
	return configClient, nil
}

func nacosLoad() {
	cfgDataId := "flare-application"
	if s, exists := os.LookupEnv("FLARE_MODE"); exists {
		switch s {
		case "dev":
			// do nothing, use default cfgDataId
		case "local":
			cfgDataId = "flare-application-local"
		case "cluster":
			cfgDataId = "flare-application"
		}
	}
	config, err := NacosClient.GetConfig(vo.ConfigParam{
		DataId: cfgDataId,
		Group:  "DEFAULT_GROUP",
	})
	if err != nil {
		panic(err)
	}
	v := viper.New()
	v.SetConfigType("yaml")
	if err := v.ReadConfig(strings.NewReader(config)); err != nil {
		logrus.Fatalf("[nacosLoad] - read config failed: %v", err)
	}
	if err := v.Unmarshal(&ApplicationCfg); err != nil {
		logrus.Fatalf("[nacosLoad] - unmarshal config failed: %v", err)
	}
	logrus.Infof("[nacosLoad] - Nacos configuration loaded successfully, %s", cfgDataId)
}
